<?php
namespace control;
/*
*期末结转凭证设置表
*/


class carryoverClass extends adIndexClass
{
    private const page = 'carryover';
    private const table = 'period_end_setting';
    private const tableMx = 'period_end_setting_detail';
    private const title = '期末结转凭证设置表';
    private const ruleOption = ['余额'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "模板名称" => text(array("name" => "name")),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . " and isDel = 0";
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time asc"));
        //获取表头
        //获取记录
        $html = "<ul class='tag-list-ul'>";
        $root = root;
        foreach ($page['array'] as $array) {
            $html .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 <span class="tag-contain-title-text">{$array['name']}</span>
           </div>
           <div class="tag-contain-body">
                 <ul class="tag-contain-ul">
                     <li></li>
                 </ul>
           </div>
           <div class="tag-contain-foot">
           </div>
           <div class="tag-edit-content">
                 <img class="right" onclick="layer('carryover','settingPage',{id:'{$array['id']}'})" alt="" src="{$root}img/control/setting.svg">
<!--                 <span class="spanButton li-btn-blue-bg" onclick="newIframe('录凭证',root+'control/adIndex.html?cla=voucherEdit&fun=home&method=endPeriod&sourceId={$array['id']}')">生成凭证</span>-->
           </div>
     </div>
</li>
efo;
        }
        $html .= <<<efo
</ul>
efo;
        $html .= $this->style();
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $html . "</form>" . space . $page['button'] . clear;
        return json_encode($json, 320);
    }


    public function settingPage()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        $wordSelect = idSelect(array('name' => 'voucherWordId', 'class' => 'select', 'value' => $info['voucherWordId'], 'title' => '请选择', 'sqlForm' => "voucher_word where coid = '" . self::$coid . "'", 'sqlId' => 'id', 'sqlField' => 'word'));
        $tr[] = ['', '摘要', '会计科目', '方向'];
        $all = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
        foreach ($all['array'] as $k=>$array) {
            $subject = query('subject',"id = '$array[subjectId]'");
            $direction = select(array('name' => 'direction[]',  'value' => $array['direction'], 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select'));
//            if ($subject['direction'] == $array['direction']) {
//                $ruleOption = text(array('name' => 'rule[]', 'value' => $array['rule'], 'class' => 'textPrice', 'title' => '百分比')) . '%';
//            } else {
//                $ruleOption = select(array('name' => 'rule[]', 'value' => $array['rule'], 'title' => '请选择', 'option' => self::ruleOption, 'class' => 'select'));
//            }
            $subjectSelect = text(array('name' => 'subjectName[]', 'value' => $subject['code'] . '-' . $subject['name'], 'class' => 'text', 'id' => $array['id'], 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => $array['subjectId'])) . <<<eof
<script>
$("#{$array['id']}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
       e.parent().parent().find("[name='direction[]']").val(data.direction)
       // $.post(root+'control/adIndex.html?cla=carryover&fun=getRule',{direction:data.direction},function(res) {
       //      e.parent().parent().find("td").eq(3).empty().append(res.html)
       // },'json')
}}) 
</script>
eof;
            $tr[] = [
                componentClass::tablePperation($k+1,"delTableRow(this)").
                hidden(array('name' => 'mxId[]', 'value' => $array['id'])),
                text(array('name' => 'summary[]', 'class' => 'text', 'value' => $array['summary'])),
                $subjectSelect,
                $direction
            ];
        }
        $table = $this->tableMany(array('tr' => $tr, 'end' => true, 'button' => true, 'method' => "addRow(this)"));
        //生成表单
        $html = <<<eof
<form name="templateForm">
<div style="padding:10px 20px">
    <div style="display: flex;flex-direction: row;justify-content: space-between">
        <div>模板名称：<input name="templateName" class="select" value="{$info['name']}" /></div>
        <div>凭证字：$wordSelect</div>
    </div>
    <div style="padding: 10px 0;margin-top: 10px;height: 400px;overflow: auto">
        $table
    </div>
    <input type="hidden" name="id" value="$id">
</div>
<script>
function addRow(e) {
    $.post(root+'control/adIndex.html?cla=carryover&fun=addRow',{},function (res){
             $(e).parent().before(res.html);
             resetNumber($(e).parent().parent())
    },'json');
}
function getRule(e){
     let subjectId =  $(e).parent().parent().find("[name='subjectId[]']").val();
     $.post(root+'control/adIndex.html?cla=carryover&fun=getRule',{direction:e.value,subjectId:subjectId},function(res) {
            $(e).parent().parent().find("td").eq(3).empty().append(res.html)
       },'json')
}
</script>
</form>
eof;
        $button = "<input class=\"button\" onclick=\"subForm('templateForm',root+'control/adIndex.html?cla=carryover&fun=settingSave')\" type=\"button\" value=\"保存\"/>";
        //返回
        return $this->layer(array("title" => "编辑", "height" => 600, "width" => 900, "html" => $html, "button" => $button));
    }

    /**
     * 根据方向获取规则
     */
    public function getRule()
    {
        $direction = $this->post('direction');
        $subject = query('subject',"id = '".$this->post('subjectId')."'");
        if ($subject['direction'] == $direction) {
            $json['html'] = text(array('name' => 'rule[]', 'class' => 'textPrice', 'title' => '百分比')) . '%';
        } else {
            $json['html'] = select(array('name' => 'rule[]',  'title' => '请选择', 'option' => self::ruleOption, 'class' => 'select'));
        }
        return json_encode($json, 320);
    }

    /**
     * 配置保存
     */
    public function settingSave()
    {
        $id = $this->post('id')?:self::getId();

        $mxIds = $this->post('mxId');
        $directions = $this->post('direction');
//        $ruleTexts = $this->post('rule');
        $subjectIds = $this->post('subjectId');
        $summarys = $this->post('summary');

        $field = [
            'name' => $this->post('templateName'),
            'voucherWordId' => $this->post('voucherWordId'),
        ];
        $annotation = [
            'name' => '模板名称',
            'voucherWordId' => '凭证字',
        ];

        $rules = [
            'name' => 'required',
            'voucherWordId' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }

//        $flag = false;
//        $percent = 0;
//        if (is_array($mxIds)){
//            foreach ($mxIds as $k=>$val){
//                $subject = query('subject',"id = '$subjectIds[$k]'");
//                if ($subject['direction'] ==$directions[$k]){
//                    $ruleTexts[$k] = $ruleTexts[$k]?:0;
//                    $percent+=$ruleTexts[$k];
//                    $flag = true;
//                }
//            }
//        }

        if (!$this->power(self::page, "edit") && !$this->power('carryoverCustomize', "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => 'salary_setting', 'where' => " and id !='$id' and name = '$field[name]' and coid = '" . self::$coid . "'")) > 0) {
            $json['warn'] = '已存在相同名称的模板';
        } elseif (static::is_null_array($mxIds)) {
            $json['warn'] = '请填写凭证规则';
        } elseif (static::is_null_array($summarys)) {
            $json['warn'] = '请填写摘要';
        } elseif (static::is_null_array($subjectIds)) {
            $json['warn'] = '请选择科目';
        } elseif (static::is_null_array($directions)) {
            $json['warn'] = '请选择方向';
        }  else {
            $this->startTrans();
            $where = " id = '$id' ";
            $voucherWord = query('voucher_word', "id = '$field[voucherWordId]'");
            $field['voucherWord'] = $voucherWord['word'];
            $info = query(self::table, $where);
            if (!$info['id']) {
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'isDel' => 1
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            foreach ($mxIds as $k => $mxId) {
                $mx = query(self::tableMx, "id = '$mxId'");
                if (empty($mx['id'])) {
                    $warn = static::insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id' => $mxId,
                            'coid' => self::$coid,
                            'orderId' => $id,
                            'subjectId' => $subjectIds[$k],
                            'summary' => $summarys[$k],
                            'direction' => $directions[$k],
//                            'rule' => $ruleTexts[$k]?:0,
                        ]
                    ));
                } else {
                    $warn = static::update(array(
                        'table' => self::tableMx,
                        'field' => [
                            'subjectId' => $subjectIds[$k],
                            'direction' => $directions[$k],
                            'summary' => $summarys[$k],
//                            'rule' => $ruleTexts[$k]?:0,
                        ],
                        'where' => "id = '$mxId'"
                    ));
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $json['warn'] = $warn;
                    break;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => "orderId = '$id' and id not in ('" . implode("','", $mxIds) . "')"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);

    }

    /**
     * 添加一行
     * @return false|string
     */
    public function addRow()
    {
        $suiji = suiji();
        $direction = select(array('name' => 'direction[]', 'title' => '请选择', 'option' => ['借', '贷'], 'class' => 'select'));
//        $ruleOption = select(array('name' => 'rule[]', 'title' => '请选择', 'option' => self::ruleOption, 'class' => 'select'));
        $subjectSelect = text(array('name' => 'subjectName[]', 'class' => 'text', 'id' => $suiji, 'title' => '请选择')) . hidden(array('name' => 'subjectId[]', 'value' => '')) . <<<eof
<script>
$("#{$suiji}").bigAutocomplete({
    url:root + 'control/adIndex.html?cla=component&fun=getSubject',
    callback:function(data,e){
       e.siblings("input[name='subjectId[]']").val(data.id)
        e.parent().parent().find("[name='direction[]']").val(data.direction)
}}) 
</script>
eof;
        $tr[]              = [
            componentClass::tablePperation('',"delTableRow(this)").
            hidden(array('name' => 'mxId[]', 'value' => $suiji)),
            text(array('name' => 'summary[]','class' => 'text')),
            $subjectSelect,
            $direction
        ];
        $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
        return json_encode($json, 320);
    }


    /**
     * 样式
     */
    private function style(): string
    {
        return <<<eof
<style>
.tag-list-ul>li{float: left;padding: 5px;margin: 5px}
.tag-contain{width: 250px;height: 130px;padding: 10px;border: 1px solid #d7d7d7;border-radius: 2px;position: relative;overflow: hidden}
.tag-contain-title-text{margin-left: 10px;font-weight: bold;font-size: 14px}
.tag-contain-body{padding: 10px;}
.tag-contain-ul li{padding: 35px 20px 0 20px;font-size: 13px}
.tag-contain-foot{padding: 10px;border-bottom: 1px solid #d7d7d7}
.tag-edit-content .spanButton{float: right}
.tag-edit-content img:nth-child(1){width: 22px;cursor: pointer;margin-top: 10px}
.label-edit-ul li{float: left}
.add-attr-button{border: 2px solid #6aacfb;margin-top: 5px;color: #6aacfb;font-weight: bold;font-size: 21px; width: 16px;height: 16px;text-align: center;line-height: 13px;cursor: pointer;border-radius: 2px;

}
</style>
eof;

    }

    /*列表页-查询条件*/
    public function customizeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "模板名称" => text(array("name" => "name")),
                ],
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function customize()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power('carryoverCustomize', "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','settingPage',{id:'" . suiji() . "'})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power('carryoverCustomize', "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    public function customizeSearch()
    {
        //like查询数组
        $like = array(
            "name" => $this->post('name'),
        );
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . " and isDel = 1";
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time asc"));
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取表头
        //获取记录
        $html = "<ul class='tag-list-ul'>";
        $root = root;
        foreach ($page['array'] as $array) {
            $box = "<input name=\"listId[]\" type=\"checkbox\" value=\"$array[id]\">";
            $html .= <<<efo
<li>
     <div class="tag-contain">
           <div class="tag-contain-title">
                 $box
                 <span class="tag-contain-title-text">{$array['name']}</span>
           </div>
           <div class="tag-contain-body">
                 <ul class="tag-contain-ul">
<!--                     <li>金额：<span>0</span></li>-->
                 </ul>
           </div>
           <div class="tag-contain-foot">
           </div>
           <div class="tag-edit-content">
                 <img class="right" onclick="layer('carryover','settingPage',{id:'{$array['id']}'})" alt="" src="{$root}img/control/setting.svg">
<!--                 <span class="spanButton li-btn-blue-bg">生成凭证</span>-->
           </div>
     </div>
</li>
efo;
        }
        if (is_array($page['array']) && count($page['array']) == 0) {
            $html .= <<<efo
<li>
     <div style="width: 100%;height: 50px;line-height: 50px">
      一条数据也没有
     </div>
</li>
efo;
        }
        $html .= <<<efo
</ul>
efo;
        $html .= $this->style();
        //控件
        $button = "";
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='customizeForm'>" . $html . "</form>" . space . $page['button'] . clear;
        return json_encode($json, 320);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, customizeForm';
                $power = '';
                break;
        }
        if (!$this->power('carryoverCustomize', $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=customize',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power('carryoverCustomize', "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if (!$info['isDel']) {
                    //返回
                    $warn = "删除失败：系统预设模板不能删除\n";
                } elseif (static::total(array('table' => 'voucher', 'where' => "sourceId = '$id'")) > 0) {
                    $warn = "删除失败：此模板已被使用\n";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => 'carryoverCustomize', "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

